package com.example.controller;/**
 * @Author kzc
 * @Date 2023/4/18 21:22 （可以根据需要修改）
 * @作用
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.example.VO.wxuse;
import com.example.config.WechatUtil;
import com.example.domain.Users;
import com.example.tools.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @作用: business
 *
 * @说明:
 *
 * @author: kzc
 *
 * @日期: 2023-04-18 21:22
 **/

@RestController
@RequestMapping("/system")
public class login {
    @PostMapping("/wx/login")
    public Result user_login(@RequestParam(value = "code", required = false) String code,
                        @RequestParam(value = "rawData", required = false) String rawData,
                        @RequestParam(value = "signature", required = false) String signature) {
        // 用户非敏感信息：rawData
        // 签名：signature
        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");

        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        if (!signature.equals(signature2)) {
            return Result.fail().message("签名校验失败");
        }
        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；
//        LambdaQueryWrapper<wxuse> lqw = Wrappers.lambdaQuery();
//        lqw.eq(User::getOpenId, openid);
//        User user = userService.getOne(lqw);
//        if (user == null) {
            // 用户信息入库
            String nickName = rawDataJson.getString("nickName");
            String avatarUrl = rawDataJson.getString("avatarUrl");
        wxuse wxuse = new wxuse();
        wxuse.setOpenId(openid);
        wxuse.setAvatar(avatarUrl);
        wxuse.setNickName(nickName);
//            userService.save(user);

        return Result.ok(wxuse);
    }


//@ApiOperation(value = "微信小程序自动登录/注册")
//@GetMapping("/wxauth/signin/{code}")
//public Result<String> doWxLogin(@PathVariable @ApiParam(value = "wx.login获取的登录凭证",required = true) String code){
//    return authService.doWxLogin(code);
//}


}
